package com.elinkway.infinitemovies.ui.activity.play;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.os.Handler;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.Utils;
import com.le123.ysdq.R;
import com.novaplayer.LetvMediaPlayerControl;

import java.util.Formatter;
import java.util.Locale;

/**
 * Created by biandi on 2017/8/4.
 */
public class WebVideoPlayerGestureHandle {
    private final String TAG = WebVideoPlayerGestureHandle.class.getSimpleName();

    /**
     * 最大拖动时间 2分钟
     */
    private final static int MAXSEEKTIME = 2 * 60;
    /**
     * 最大系统音量
     */
    private final static int VOLUME_MAX = 1500 ;

    private final String BRIGHTNESS = "brightness";
    private final String VOLUME = "volume";
    private final String FORWARD_IMAGEVIEW = "forward";
    private final String BACKWARD_IMAGEVIEW = "backward";
    private final String GESTUREGUIDE = "gestureguide";
    private final String GESTUREGUIDE_INDEX = "gestureguideindex";
    /**
     * 手势滑动时的起始X坐标
     */
    private float mStartXPoint;
    /**
     * 手势滑动时的起始Y坐标
     */
    private float mStartYPoint;

    private Handler mHandler ;
    private Activity mActivity;
    /**
     * 全屏播放页面布局
     */
    private View mFullScreenLayout;
    /**
     * 屏幕宽度
     */
    private int mWindowWidth ;
    /**
     * 屏幕高度
     */
    private int mWindowHeight;
    /**
     * 左右滑屏
     */
    private boolean mSlideLeftAndRight;
    /**
     * 上下滑屏
     */
    private boolean mSlideUpAndDown;
    /**
     * 当前的屏幕亮度
     */
    private float mCurrentBrightness = -1f;
    /**
     * 当前的音量值
     */
    private int mCurrentVolume = -1;
    /**
     * 当前的播放时间
     */
    private int mCurrentPosition;

    /**
     * 音频管理器，用于调节手机音量
     */
    private AudioManager mAudioManager;
    /**
     * 显示手势拖动时的文字
     */
    private TextView mGestureDragTextView;
    /**
     * 显示手势拖动时的图片
     */
    private ImageView mGestureImageView;
    /**
     * 手势拖动时用到的弹窗
     */
    public PopupWindow mGesturePopupWindow;
    /**
     * 手势引导时用到的弹窗
     */
    public PopupWindow mGestureGuidePopupWindow;
    /**
     * 手势拖动时显示什么图片，快进、快退、音量或者亮度图片
     */
    private String mGestureImageViewFlag;

    private Bitmap mGestureGuideBitmap;

    private WebVideoController mediaController;

    private SharedPreferences gestureGuidePreferences;

    public WebVideoPlayerGestureHandle(Activity activity, Handler handler,WebVideoController mediaController,View layout){
        mActivity = activity;
        mHandler = handler;
        this.mediaController = mediaController;
        mFullScreenLayout = layout;
        mWindowWidth = Utils.getWidthPixels(mActivity);
        mWindowHeight = Utils.getHeightPixels(mActivity);

        initGestureView();
    }

    /**
     * 初始化手势拖动时用到的图片和文字背景
     */
    private void initGestureView() {
        if(null == mActivity){
            return ;
        }
        LayoutInflater layoutInflater = mActivity.getLayoutInflater();
        if(null == layoutInflater){
            return ;
        }

        View gestureView = layoutInflater.inflate(R.layout.player_gesture_drag, null);
        if(null != gestureView){
            mGestureDragTextView = (TextView)gestureView.findViewById(R.id.gesture_textview);
            mGestureImageView = (ImageView)gestureView.findViewById(R.id.gesture_imageview);
            mGesturePopupWindow = new PopupWindow(gestureView, FrameLayout.LayoutParams.WRAP_CONTENT,
                    FrameLayout.LayoutParams.WRAP_CONTENT);
        }
    }

    /**
     * 处理手势滑动的相关操作
     * ACTION_DOWN 和 ACTION_UP事件只会执行一次，
     * @param event:滑动事件
     */
    public void handleGestureSlide(MotionEvent event){
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            mStartXPoint = event.getX();
            mStartYPoint = event.getY();
            initGestureData();
        }
        else if(event.getAction() == MotionEvent.ACTION_MOVE){
            float endXPoint = event.getX(); //手势滑动时的结束X坐标
            float endYPoint = event.getY(); //手势滑动时的结束Y坐标
            if(Math.abs(mStartXPoint - endXPoint) >= Math.abs(mStartYPoint - endYPoint) &&  mSlideLeftAndRight
                    && Math.abs(mStartXPoint - endXPoint) >= 90) {//50是个概数，满足一定的滑动距离才进入手势滑动状态
                gestureBackAndForword(mStartXPoint,endXPoint);

            }else if(Math.abs(mStartXPoint - endXPoint) < Math.abs(mStartYPoint - endYPoint)
                    && mSlideUpAndDown
                    && Math.abs(mStartYPoint - endYPoint) >= 90){
                gestureUpAndDown(mStartYPoint, endYPoint);
            }
        }
        else if (event.getAction() == MotionEvent.ACTION_UP){
            LogUtils.i(TAG,"***** in event.getAction() == MotionEvent.ACTION_UP *****");
            //销毁手势弹窗
            if(null != mGesturePopupWindow && mGesturePopupWindow.isShowing()){
                LogUtils.i(TAG,"***** in MotionEvent.ACTION_UP before sendMessage*****");
                mHandler.removeMessages(Utils.VIDEO_DISMISS_GESTURE_POPUPWINDOW);
                mHandler.sendEmptyMessageDelayed(Utils.VIDEO_DISMISS_GESTURE_POPUPWINDOW,
                        Utils.VIDEO_DISMISS_GESTURE_POPUPWINDOW_TIME);
            }
        }
    }

    /**
     * 初始化手势滑动的初始值
     */
    private void initGestureData(){
        if(null == mActivity){
            return ;
        }
        if(null == mAudioManager){
            mAudioManager = (AudioManager)mActivity.getSystemService(Context.AUDIO_SERVICE);
        }
        mCurrentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        mCurrentBrightness = mActivity.getWindow().getAttributes().screenBrightness;
        mCurrentPosition = mediaController.getCurrentPosition();
        mSlideUpAndDown = true;//ACTION_DOWN时，将两个标志位都置为true，根据第一次滑动时哪个方向的偏移量大，分别进行左右滑屏或者上下滑屏
        mSlideLeftAndRight = true;
    }

    /**
     * 手势快进和快退
     */
    private void gestureBackAndForword(float startX, float endX){
        mSlideUpAndDown = false;
        if(mWindowWidth > 0){
            float percent = (endX -startX) / mWindowWidth;
            gestureSeekTo(percent);
        }

    }
    /**
     * 手势调节音量和亮度
     */
    private void gestureUpAndDown(float startY,float endY){
        mSlideLeftAndRight = false;
        float percent = (startY - endY) / (2 * mWindowHeight / 3);// 2/3的屏幕拖动，要完成音量或者屏幕亮度从0%-100%的变化
        if(mStartXPoint >= (mWindowWidth / 2)){//滑屏发生在右半屏，处理音量变化
            gestureVolumeHandle(percent);
        }else{
            gestureBrightnessHandle(percent);
        }
    }

    /**
     * 处理手势seekto操作
     */
    private void gestureSeekTo(float percent){
        int positionIndex = (int)(percent * MAXSEEKTIME) ;
        if(positionIndex > MAXSEEKTIME){
            positionIndex = MAXSEEKTIME;
        }else if(positionIndex < -MAXSEEKTIME){
            positionIndex = -MAXSEEKTIME;
        }

        int destPosition = mCurrentPosition + positionIndex;
        int duration = mediaController.getDuration();
        if(destPosition >= duration){
            destPosition = duration;
        }else if(destPosition <= 0){
            destPosition = 0;
        }

        mediaController.onSeekTo(destPosition);
        if(null != mediaController){
            mediaController.refreshPlaySeekBar();
        }

        if(percent >= 0){
            mGestureImageViewFlag = FORWARD_IMAGEVIEW;
        }else{
            mGestureImageViewFlag = BACKWARD_IMAGEVIEW;
        }
        int position = mediaController.getCurrentPosition();
        String html="<html><body><font color=\"#aabb00\">颜色1</body></html>";
        Html.fromHtml(html);
        showGestureTimeAndVolume(mGestureImageViewFlag,
                toStringTime(position),
                "/"+toStringTime(duration));
    }

    /**
     * 返回00:00格式
     *
     * @param time 单位：秒
     * @return
     */
    public static String toStringTime(int time) {
        StringBuilder formatBuilder = new StringBuilder();
        Formatter formatter = new Formatter(formatBuilder, Locale.getDefault());
        try {
            if (time <= 0) {
                time = 0;
            }
            int totalSeconds = time;
            int seconds = totalSeconds % 60;
            int minutes = totalSeconds / 60;
            formatBuilder.setLength(0);
            String currtime = formatter.format("%02d:%02d", minutes, seconds)
                    .toString();
            return currtime;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            formatter.close();
        }
        return null;
    }

    /**
     *  处理屏幕亮度操作
     */
    private void gestureBrightnessHandle(float percent){
        if(mCurrentBrightness < 0){
            mCurrentBrightness = mActivity.getWindow().getAttributes().screenBrightness;
            if(mCurrentBrightness <= 0.00f)
                mCurrentBrightness = 0.50f;
            if(mCurrentBrightness < 0.01f)
                mCurrentBrightness = 0.009f;
        }

        mGestureImageViewFlag = BRIGHTNESS;
        WindowManager.LayoutParams lParam = mActivity.getWindow().getAttributes();
        lParam.screenBrightness = mCurrentBrightness + percent;
        if (lParam.screenBrightness > 1.0f){
            lParam.screenBrightness = 1.0f;
        }else if (lParam.screenBrightness < 0.01f){
            lParam.screenBrightness = 0.009f;
        }

        mActivity.getWindow().setAttributes(lParam);
        showGestureTimeAndVolume(mGestureImageViewFlag,(int)(lParam.screenBrightness * 100)  + "%",null);
    }

    /**
     *  手势音量操作
     */
    private void gestureVolumeHandle(float percent){
        if(mCurrentVolume == -1 && null != mAudioManager){
            mCurrentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            if(mCurrentVolume < 0){
                mCurrentVolume = 0;
            }
        }

        mGestureImageViewFlag = VOLUME;
        int volumeIndex = (int)(percent * VOLUME_MAX) + mCurrentVolume * 100; //用于匹配进度条可以从0%-100%变化
        float v = percent+ (float)mCurrentVolume * 100/VOLUME_MAX;
        String result = String .format("%.1f",v);
        mediaController.setCurrentVolume(result);
        int volumeShowOnText = 100 * volumeIndex / VOLUME_MAX;
        if(volumeShowOnText > 100)
            volumeShowOnText = 100;
        else if(volumeShowOnText < 0)
            volumeShowOnText = 0;

        volumeIndex = volumeIndex / 100;
        if (volumeIndex > 15)
            volumeIndex = 15;
        else if (volumeIndex < 0)
            volumeIndex = 0;
        showGestureTimeAndVolume(mGestureImageViewFlag,volumeShowOnText + "%",null);
    }

    /**
     * 显示手势拖动时的弹窗
     */
    private void showGestureTimeAndVolume(String imageViewBg,String textViewShowed,String forwardText){
        if(null == mGestureDragTextView || null == mGestureImageView
                || null == mGesturePopupWindow){
            return ;
        }

        if(imageViewBg == BRIGHTNESS){
            mGestureImageView.setImageResource(R.drawable.gesture_brightness);
            mGestureDragTextView.setText(textViewShowed);
        }else if(imageViewBg == VOLUME){
            mGestureImageView.setImageResource(R.drawable.gesture_volume);
            mGestureDragTextView.setText(textViewShowed);
        }else if(imageViewBg == FORWARD_IMAGEVIEW){
            mGestureImageView.setImageResource(R.drawable.gesture_forward);
            String html="<html><body><font color=\"#1283f6\">"+textViewShowed+"</font><font>"+forwardText+"</font></body></html>";
            mGestureDragTextView.setText(Html.fromHtml(html));
        }else if(imageViewBg == BACKWARD_IMAGEVIEW){
            mGestureImageView.setImageResource(R.drawable.gesture_backward);
            String html="<html><body><font color=\"#1283f6\">"+textViewShowed+"</font><font>"+forwardText+"</font></body></html>";
            mGestureDragTextView.setText(Html.fromHtml(html));
        }
        if(null != mFullScreenLayout){
            int[] location = new int[2];
            mFullScreenLayout.getLocationOnScreen(location);
            View view = mGesturePopupWindow.getContentView();
            int w =View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
            int h =View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
            view.measure(w,h);
            int height= view.getMeasuredHeight();
            int width=view.getMeasuredWidth();
            mGesturePopupWindow.showAtLocation(mFullScreenLayout, Gravity.NO_GRAVITY, location[0] + mFullScreenLayout.getWidth() / 2 - width / 2,
                    location[1] + mFullScreenLayout.getHeight() / 2 - height / 2);
        }
    }

    /**
     * 销毁手势弹窗
     */
    public void dismissGesturePopupWindow(){
        if(null != mGesturePopupWindow && mGesturePopupWindow.isShowing()){
            mGesturePopupWindow.dismiss();
        }
    }

    public void destroyResource() {
        mAudioManager = null;
        mGestureDragTextView = null;
        mGestureImageView = null;
        mGesturePopupWindow = null;
        mActivity = null;
    }

}
